<template>
	<view class="">
		<block v-if="isPrivacy">
			<xh-privacy title="隐私保护指引" theme="direction" @onHandleAgree="onHandle" background="rgba(0, 0, 0, .5)"
				color="#6C02FA"></xh-privacy>
		</block>
		<view :style="{ '--bg-image': `url(${listPoster[0].img})` }" class="bgIndex text-align_center">
			<view class="Countdown flex" style="color: #fff;">
				{{seconds}}s
			</view>
			<!-- <view class="flex-column margin-top_100rpx">
				<image class="logo" :src="ellipse" mode=""></image>
				<image class="titleLogo" src="https://n8.weijuyunke.com/2024-07-03/0b569202407030318535151.png"
					mode="aspectFit"></image>
			</view> -->

			<view v-if="showBtn" class="startNow flex"  @click="startNowFn()">
				立即开启
			</view>

		</view>
	</view>
</template>

<script>
	function unparam(str = '', unDecodeURI) {
		let result = {};
		let arr = str.split('&');
		arr.forEach((item, idx) => {
			let param = item.split('='),
				name = param[0],
				value = param[1] || '';
			if (name) {
				result[name] = unDecodeURI ? value : decodeURIComponent(value);
			}
		});

		return result;
	}
	export default {
		components: {

		},
		data() {
			return {
				userInfo: uni.getStorageSync("userInfo"),
				isPrivacy: uni.getStorageSync("privacy") ? false : true,
				ellipse: this.$img.ellipse,
				title: 'Hello',
				seconds: '',
				showBtn: false,
				listPoster: [],
				invite: '',
				basicConfiguration: {},
				access_token:'',
				openid:''



			}
		},
	
		onLoad(options) {
			this.basicConfigurationFn()
			console.log(options)
			
			// uni.showModal({
			// 	title: '提示',
			// 	content: JSON.stringify(options.invite),
			// 	success: async (res) => {
			// 		if (res.confirm) {


			// 		} else if (res.cancel) {

			// 		}
			// 	}
			// });


			// this.invite=unparam(result);
			/* 当用户扫描二维码进入小程序时，统一是scene。以pid保存（在登录页面中包含） */
			if (options.scene) {
				// unparam转对象
				let str = decodeURIComponent(options.scene);
				var inviteCode=str.substring(7)
				uni.setStorageSync('invite', inviteCode);
			}

			this.countdown(3)
			this.init()
		},
		methods: {
			onHandle(e) {
				this.isPrivacy = e;
			},
			async basicConfigurationFn() {
				const result = await this.$http.post({
					url: this.$api.config,
					data: {
					},
					headers: {

					}

				})
				if (result.code == 0) {
					console.log(result)
					this.basicConfiguration = result.data

					wx.setStorageSync('system', result.data);

 
				}
			},
			isToken() {
				setTimeout(() => {
					this.userInfoFn()
				}, 500)
				console.log('onLoad')
			},
			async userInfoFn() {
				wx.login({
					provider: 'weixin',
					success: async res => {
						console.log(res)
						const result = await this.$http.post({
							url: this.$api.getXcxUserInfo,
							data: {
                                
								code: res.code


							},
							headers: {

							}
						})

						if (result.code == 0) {
							console.log(result)
                             wx.setStorageSync('is_new_user', result.data.is_new_user);
							 uni.setStorageSync('openid', result.data.openid);
							 this.openid= result.data.openid
							 
							// 0 老用户 1 新用户
							if (result.data.is_new_user) {
								uni.removeStorageSync('userInfo')
								// this.$sun.navRe('/pages/Login/setUpChildLogin', {
								// 	...result.data
								// })
								this.$sun.navRe('/pages/home/home');
								
							} else {
								// this.$sun.navRe('/pages/home/home');
								this.gloginFn(result.data)
							}



						} else {
							this.$sun.toast(result.message)
							// this.$sun.navRe('/pages/Login/setUpChildLogin')
						}

						// 		const result = await this.$http.post({
						// 			url: this.$api.getOpenidAndSessionKey,
						// 			data: {
						// 				code: res.code,

						// 			}
						// 		});
						// 		if (result.code == 0) {
						// 			console.log('data', result.data);
						// 			this.openid = result.data.openid
						// 			this.unionid = result.data.unionid

						// 		}


					}
				});



			},
			gloginFn(data) {
				uni.request({
					url: this.$api.userLogin,
					method: 'POST',
					data: {
						
						unionid: data.unionid,
						openid: data.openid,
					

						/*  * 新增微信用户
						 * @param openid
						 * @param avatar 头像
						 * @param nickname 昵称
						 * @param dy_uid 抖音uid */
						// 微信用户opendid
						// openid: wx.getStorageSync('openid'),
						// unionid:openInfo.result.unionid,
						// // 微信用户昵称
						// // nickname: user.nickName,
						// // 独立小程序需要
						// nickname: this.nickname ? this.nickname : '默认昵称',
						// // 微信用户头像
						// avatar: this.avatarUrl ? this.avatarUrl :
						// 	'/static/avatar.png',
						// 分销pid
						// pid : pid
						// pid: uni.getStorageSync('pid') ? uni.getStorageSync('pid') : null,
						// 站点id
						// siteId: String(wx.getStorageSync('siteId')),
					},
					success: async res => {
						console.log(res)
						if (res.data.code == 0) {
                           this.openid= data.openid
							// 当前状态 为true的时候不清除

							this.$sun.toast('登录成功');
							wx.setStorageSync('userInfo', res.data
								.data);
                            uni.removeStorageSync('invite')
							setTimeout(()=>{
								this.$sun.navRe('/pages/home/home');
							},300)
							// this.test()

						} else {
							this.$sun.toast(res.data.message);
						}

					},
					fail: err => {
						uni.showModal({
							title: '错误',
							content: `访问公众平台接口失败, 错误: invalid appsecret, view more at http://t.cn/RAEkdVq, hints: [ req_id: WeMfdZyFe-D3JW7 ],错误详情：无效的appsecret`,
							showCancel: false
						});
					},
					complete: info => {
						// 由于wx.getUserProfile被删除了，所以获取不到res.user
						// wx.setStorageSync('userInfo', user);
					}
				});
			},


			countdown(seconds) {

				console.log(seconds);
				if (seconds >= 0) {
					if(seconds==1){
						this.showBtn = true
					}
					setTimeout(() => {
						this.seconds = seconds
						this.countdown(seconds - 1);
					}, 1000); // 每隔一秒执行一次
				} else {
					// this.showBtn = true
					// this.$sun.navRe('/pages/index/index')
					// this.startNowFn()
				}
			},
			startNowFn() {
				this.isToken()

			},
			// test(){
			// 	wx.request({
				
			// 	      url: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxa0ad5821a91185fc&secret=776b5bbb0757f79f9f030714761fc38f',
				
			// 	      method: 'get',
				
			// 	      success:  (res)=> {
				
			// 	        console.log(res)
			// 			this.access_token=res.data.access_token
			// 	             wx.request({
			// 	                 url: 'https://api.weixin.qq.com/wxa/msg_sec_check?access_token='+this.access_token, //这里放接口路径，
			// 	                 method:'POST',  //请求方式
			// 	                 data:{   //data里面放携带参数
			// 	                   // "access_token" : this.access_token  ,//这里根据需求写  例:"name" : "张三"
			// 					   "content":'习近平',
			// 					   "version":'2',
			// 					   'scene':'1',
			// 					   "openid":this.openid
								   
			// 	                 },
			// 	                 header:{
			// 	                   "content-type" :'application/json' //携带参数的格式，这里我们用json格式，对应上面data
			// 	                 },
			// 	                 success:res=>{  //数据请求成功执行的函数
			// 	                   console.log(res)  //成功之后返回的数据
			// 	                   this.setData({
			// 	                       listData : res.data.data  //拿到数据赋值
			// 	                   })
			// 	                 }
			// 	               })
				      
			// 	      }
				
			// 	    })
			// },
			// 获取轮播图
			async init() {
				const resPoster = await this.$http.post({
					url: this.$api.poster,
					data: {

						type: 1

					},
					headers: {
						'Authorization': `Bearer ${this.token}`
					}

				})

				if (resPoster.code == 0) {



					console.log(resPoster.data)
					// 	// 展示区域  1 首页 2 商城 3 套餐卡市场 这里还需要区分

					this.listPoster = resPoster.data.filter(item => item.type == 1);
					console.log(this.listPoster)




				} else {

					this.$sun.toast(resPoster.message, 'none')
				}



			},

		}
	}
</script>

<style lang="less" scoped>
	.bgIndex {
		position: relative;
		padding: 23rpx;
		background-repeat: no-repeat;
		background-size: cover;
		background-image: (var(--bg-image));
		height: 100vh;

		.Countdown {
			width: 64rpx;
			height: 64rpx;
			box-sizing: border-box;
			border: 2rpx solid rgb(255, 255, 255);
			border-radius: 50%;
			float: right;
		}

		.logo {
			width: 136rpx;
			height: 136rpx;
			border-radius: 50%;
		}

		.titleLogo {
			width: 500rpx;
			height: 400rpx;
		}

		.startNow {
			width: 624rpx;
			position: absolute;
			bottom: 120rpx;
			height: 100rpx;
			// margin: 0 100rpx;
			transform: translate(7%, -50%);
			border-radius: 130rpx;
			color: #fff;
			box-shadow: 0rpx 8rpx 8rpx 0rpx rgba(229, 206, 255, 0.16);
			background: linear-gradient(80.35deg, rgb(171, 81, 255) 0.143%, rgb(120, 93, 246) 99.783%);
		}


	}
</style>